var Router = require('koa-router')
var request = require('koa-request')
var parseString = require('xml2js').parseString

var router = new Router()

function xml2json(xml){
    return new Promise((resolve, reject)=>{

        parseString(xml, { explicitArray : false, ignoreAttrs : true }, function(err, result){

            var json = JSON.stringify(result)

            resolve(json)
        })
    })
}

router
    .param('page', function *(page, next){
        this.page = page

        yield next
    })
    .param('size', function *(size, next){
        this.size = size

        yield next
    })
    .get('/blog/:page/:size', function *(next){

        var blogRes = yield request({
            url: 'http://wcf.open.cnblogs.com/blog/sitehome/paged/'+this.page+'/'+this.size
        })

        this.response.type = "application/json"

        /**两种调用方式 */
        // xml2json(blogRes.body).then((result)=>{

        //     this.body = result
        // })

        this.body = yield xml2json(blogRes.body)
    })
    .param('id', function *(id, next){
        this.id = id

        yield next
    })
    .get('/detail/:id', function *(next){

        var content = yield request({
            url: 'http://wcf.open.cnblogs.com/blog/post/body/' + this.id
        })

        this.response.type = "application/json"

        this.body = yield xml2json(content.body)
    })

module.exports = router